import { Request, Response } from 'express';
import { ExpenseType, SystemParam } from '../models/Config';
import { AuthenticatedRequest } from '@/middleware/auth';
import fs from 'fs';
import path from 'path';
import { CategoryConfig, OilTypeConfig, ConfigResponse } from '@/types/config';

export class ConfigController {
  // 费用类型列表
  static async listExpenseTypes(req: Request, res: Response) {
    try {
      const userId = (req as any).user?.id;
      // 查询系统默认和用户自定义类型
      const types = await ExpenseType.find({
        $or: [{ isDefault: true }, { userId }],
      });
      return res.json(types);
    } catch (error) {
      return res.status(500).json({ message: '获取费用类型失败' });
    }
  }

  // 新增费用类型
  static async createExpenseType(req: Request, res: Response) {
    try {
      const userId = (req as any).user?.id;
      const { name, code, description } = req.body;
      const exists = await ExpenseType.findOne({ code, userId });
      if (exists)
        return res.status(400).json({ message: '费用类型编码已存在' });
      const type = new ExpenseType({
        name,
        code,
        description,
        isDefault: false,
        userId,
      });
      await type.save();
      return res.status(201).json(type);
    } catch (error) {
      return res.status(500).json({ message: '新增费用类型失败' });
    }
  }

  // 修改费用类型
  static async updateExpenseType(req: Request, res: Response) {
    try {
      const userId = (req as any).user?.id;
      const { id } = req.params;
      const { name, description } = req.body;
      const type = await ExpenseType.findOneAndUpdate(
        { _id: id, userId },
        { name, description },
        { new: true }
      );
      if (!type) return res.status(404).json({ message: '费用类型不存在' });
      return res.json(type);
    } catch (error) {
      return res.status(500).json({ message: '修改费用类型失败' });
    }
  }

  // 删除费用类型
  static async deleteExpenseType(req: Request, res: Response) {
    try {
      const userId = (req as any).user?.id;
      const { id } = req.params;
      const type = await ExpenseType.findOneAndDelete({ _id: id, userId });
      if (!type) return res.status(404).json({ message: '费用类型不存在' });
      return res.json({ message: '删除成功' });
    } catch (error) {
      return res.status(500).json({ message: '删除费用类型失败' });
    }
  }

  // 获取系统参数
  static async getSystemParam(req: Request, res: Response) {
    try {
      const { key } = req.query;
      if (!key) return res.status(400).json({ message: '缺少参数key' });
      const param = await SystemParam.findOne({ key });
      if (!param) return res.status(404).json({ message: '参数不存在' });
      return res.json(param);
    } catch (error) {
      return res.status(500).json({ message: '获取系统参数失败' });
    }
  }

  // 设置系统参数
  static async setSystemParam(req: Request, res: Response) {
    try {
      const { key, value, description } = req.body;
      if (!key || value === undefined)
        return res.status(400).json({ message: '缺少参数' });
      const param = await SystemParam.findOneAndUpdate(
        { key },
        { value, description },
        { upsert: true, new: true }
      );
      return res.json(param);
    } catch (error) {
      return res.status(500).json({ message: '设置系统参数失败' });
    }
  }
}

/**
 * @swagger
 * /api/config/categories:
 *   get:
 *     summary: 获取车辆分类配置
 *     tags: [配置]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: 获取成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 message:
 *                   type: string
 *                 data:
 *                   type: object
 *                   properties:
 *                     carType:
 *                       type: array
 *                       items:
 *                         type: object
 *                         properties:
 *                           name:
 *                             type: string
 *                           value:
 *                             type: string
 *                     motorcycle:
 *                       type: array
 *                       items:
 *                         type: object
 *                         properties:
 *                           name:
 *                             type: string
 *                           value:
 *                             type: string
 *                     commercial:
 *                       type: array
 *                       items:
 *                         type: object
 *                         properties:
 *                           name:
 *                             type: string
 *                           value:
 *                             type: string
 *                     special:
 *                       type: array
 *                       items:
 *                         type: object
 *                         properties:
 *                           name:
 *                             type: string
 *                           value:
 *                             type: string
 *                     other:
 *                       type: array
 *                       items:
 *                         type: object
 *                         properties:
 *                           name:
 *                             type: string
 *                           value:
 *                             type: string
 */
export const getCategories = async (
  _req: AuthenticatedRequest,
  res: Response<ConfigResponse<CategoryConfig>>
): Promise<void> => {
  try {
    const categoryPath = path.join(__dirname, '../config/category.json');
    const categoryData: CategoryConfig = JSON.parse(
      fs.readFileSync(categoryPath, 'utf8')
    );

    res.status(200).json({
      success: true,
      message: '获取车辆分类配置成功',
      data: categoryData,
    });
  } catch (error) {
    console.error('getCategories error:', error);
    res.status(500).json({
      success: false,
      message: '获取车辆分类配置失败',
      data: {} as CategoryConfig,
    });
  }
};

/**
 * @swagger
 * /api/config/oil-types:
 *   get:
 *     summary: 获取燃油类型配置
 *     tags: [配置]
 *     security:
 *       - bearerAuth: []
 *     responses:
 *       200:
 *         description: 获取成功
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 success:
 *                   type: boolean
 *                 message:
 *                   type: string
 *                 data:
 *                   type: object
 *                   properties:
 *                     gasoline:
 *                       type: array
 *                       items:
 *                         type: object
 *                         properties:
 *                           name:
 *                             type: string
 *                           value:
 *                             type: string
 *                     ethanolGasoline:
 *                       type: array
 *                       items:
 *                         type: object
 *                         properties:
 *                           name:
 *                             type: string
 *                           value:
 *                             type: string
 *                     diesel:
 *                       type: array
 *                       items:
 *                         type: object
 *                         properties:
 *                           name:
 *                             type: string
 *                           value:
 *                             type: string
 *                     other:
 *                       type: array
 *                       items:
 *                         type: object
 *                         properties:
 *                           name:
 *                             type: string
 *                           value:
 *                             type: string
 */
export const getOilTypes = async (
  _req: AuthenticatedRequest,
  res: Response<ConfigResponse<OilTypeConfig>>
): Promise<void> => {
  try {
    const oilPath = path.join(__dirname, '../config/oil.json');
    const oilData: OilTypeConfig = JSON.parse(fs.readFileSync(oilPath, 'utf8'));

    res.status(200).json({
      success: true,
      message: '获取燃油类型配置成功',
      data: oilData,
    });
  } catch (error) {
    console.error('getOilTypes error:', error);
    res.status(500).json({
      success: false,
      message: '获取燃油类型配置失败',
      data: {} as OilTypeConfig,
    });
  }
};
